using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebRobot.App_code;
using System.IO;
using Robot.Business;
using Robot.Data;
using Robot.Entities;
using Scb.Framework;

namespace WebRobot.Pages
{
  public partial class makersite : BasePage
  {

    #region Event

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
      lbStatus.InnerHtml = "";
      if (ulfReportFX.HasFile || ulfReportITT.HasFile || ulfReportOLT.HasFile || ulfReportOTT.HasFile)
      {
        gvFileUpload.Visible = true;
        UploadFileReport();
      }

    }

    #endregion

    #region Helper

    private void UploadFileReport()
    {
      string myPath = "";
      tblFileUploadCollection listFileNewUpload = new tblFileUploadCollection();

      HttpFileCollection hfc = Request.Files;

      int countFile = 0;
      for (int i = 0; i < hfc.Count; i++)
      {
        HttpPostedFile hpf = hfc[i];


        if (hpf.ContentLength > 0)
        {
          FXFile fx = new FXFile();
          tblFileUpload file = new tblFileUpload();



          file.UploadDate = DateTime.Now;
          file.FileName = hpf.FileName.ToString().Split('.')[0] + " " + ((DateTime)file.UploadDate).ToString("yyyyMMddHHmmss") + ".pdf";
          file.UploadBy = CurrentUser.Peoplewise;

          #region File Fx

          if (i == 0)
          {
            try
            {
              fx.FileName = file.FileName;
              myPath = Server.MapPath("~") + GetValueInXML("PathFileFX") + DateTime.Today.ToString("yyyyMMdd");

              if (!Directory.Exists(myPath))
              {
                Directory.CreateDirectory(myPath);
              }
              myPath = myPath + "\\" + Path.GetFileName(file.FileName);
              file.FileName = Path.GetFileName(file.FileName);
              hpf.SaveAs(myPath);
              file.Path = myPath;
              file.FileType = 0;//FX file

              tblFileUploadService.CreatetblFileUpload(file);
              listFileNewUpload.Add(file);
              tblImportTransactionCollection tranCol = new tblImportTransactionCollection();
              tranCol = ReadReportFX(myPath);

              if (tranCol.Count > 0)
              {
                countFile++;
              }
            }
            catch (Exception ex)
            {
              tblFileUploadService.DeletetblFileUpload(file.ID);
              listFileNewUpload.Remove(file);
              File.Delete(file.Path);
              Logger.Error("WebRobot.Pages.ImportPage::UploadFileReport.FX", ex);
            }
          }
          #endregion

          #region File OTT

          else if (i == 1)
          {
            try
            {

              OtherFileReport other = new OtherFileReport();
              other.FileName = file.FileName;
              other.FileType = "ITT";

              myPath = Server.MapPath("~") + GetValueInXML("PathFileOTT") + DateTime.Today.ToString("yyyyMMdd");

              if (!Directory.Exists(myPath))
              {
                Directory.CreateDirectory(myPath);
              }
              myPath = myPath + "\\" + Path.GetFileName(file.FileName);
              file.FileName = Path.GetFileName(file.FileName);
              hpf.SaveAs(myPath);
              file.Path = myPath;
              file.FileType = 1;//Not FX
              tblFileUploadService.CreatetblFileUpload(file);
              listFileNewUpload.Add(file);
              tblImportTransactionCollection tranCol = new tblImportTransactionCollection();
              tranCol = ReadReportOther(myPath);
              if (tranCol.Count > 0)
              {
                countFile++;
              }
            }
            catch (Exception ex)
            {
              tblFileUploadService.DeletetblFileUpload(file.ID);
              listFileNewUpload.Remove(file);
              File.Delete(file.Path);
              Logger.Error("WebRobot.Pages.ImportPage::UploadFileReport.OTT", ex);
            }
          }
          #endregion

          #region File ITT
          else if (i == 2)
          {
            try
            {
              OtherFileReport other = new OtherFileReport();
              other.FileName = file.FileName;
              other.FileType = "ITT";

              myPath = Server.MapPath("~") + "\\Files\\ITT\\" + DateTime.Today.ToString("yyyyMMdd");

              if (!Directory.Exists(myPath))
              {
                Directory.CreateDirectory(myPath);
              }
              myPath = myPath + "\\" + Path.GetFileName(file.FileName);
              file.FileName = Path.GetFileName(file.FileName);
              hpf.SaveAs(myPath);
              file.Path = myPath;
              file.FileType = 1;//Not FX
              tblFileUploadService.CreatetblFileUpload(file);
              listFileNewUpload.Add(file);
              tblImportTransactionCollection tranCol = new tblImportTransactionCollection();
              tranCol = ReadReportOther(myPath);
              if (tranCol.Count > 0)
              {
                countFile++;
              }
            }
            catch (Exception ex)
            {
              tblFileUploadService.DeletetblFileUpload(file.ID);
              listFileNewUpload.Remove(file);
              File.Delete(file.Path);
              Logger.Error("WebRobot.Pages.ImportPage::UploadFileReport.ITT", ex);
            }
          }
          #endregion

          #region File OLT
          else if (i == 3)
          {
            try
            {
              OtherFileReport other = new OtherFileReport();
              other.FileName = file.FileName;
              other.FileType = "ITT";

              myPath = Server.MapPath("~") + "\\Files\\OLT\\" + DateTime.Today.ToString("yyyyMMdd");

              if (!Directory.Exists(myPath))
              {
                Directory.CreateDirectory(myPath);
              }
              myPath = myPath + "\\" + Path.GetFileName(file.FileName);
              file.FileName = Path.GetFileName(file.FileName);
              hpf.SaveAs(myPath);
              file.Path = myPath;
              file.FileType = 1;// not FX
              tblFileUploadService.CreatetblFileUpload(file);
              listFileNewUpload.Add(file);
              tblImportTransactionCollection tranCol = new tblImportTransactionCollection();
              tranCol = ReadReportOther(myPath);
              if (tranCol.Count > 0)
              {
                countFile++;
              }
            }
            catch (Exception ex)
            {
              tblFileUploadService.DeletetblFileUpload(file.ID);
              listFileNewUpload.Remove(file);
              File.Delete(file.Path);
              Logger.Error("WebRobot.Pages.ImportPage::UploadFileReport.OLT", ex);
            }
          }
          #endregion



        }
      }
      if (countFile > 0)
      {
        gvFileUpload.DataSource = listFileNewUpload;
        gvFileUpload.DataBind();
        lbStatus.InnerHtml = "Upload sucessful " + countFile.ToString() + " File!";
        lbStatus.Style.Add(HtmlTextWriterStyle.Color, "Blue");
      }
      else
      {
        lbStatus.InnerHtml = "Upload error!";
        lbStatus.Style.Add(HtmlTextWriterStyle.Color, "Red");
      }
    }

    private bool CheckReportType(string sFileName)
    {
      if (Path.GetExtension(sFileName).ToLower() != ".pdf")
      {
        lbStatus.InnerHtml = "Only .pdf file allowed!";
        return false;
      }
      return true;
    }

    public tblImportTransactionCollection ReadReportFX(string sFilePath)
    {
      FXFile fx = new FXFile();
      string sFileName = sFilePath.Split('\\')[sFilePath.Split('\\').Length - 1];
      fx.FileName = sFileName;
      string fullPath = sFilePath;
      tblImportTransactionCollection traxColection = new tblImportTransactionCollection();
      string branch = "";
      string cusName = "";
      string text = BasePage.PdfToText(fullPath); int t = 0;
      try
      {
        using (StringReader lines = new StringReader(text))
        {
          string line = "";
          while ((line = lines.ReadLine()) != null)
          {
            if (line != "")
            {
              if (fx.IsBranchCodeFX(line))
              {
                branch = fx.GetBranchFX(line);
              }
              else if (fx.IsCusName(line))
              {
                cusName = fx.GetCustumerNameFX(line);
              }
              else if (fx.IsTransaction(line))
              {
                t++;
                tblImportTransaction trax = new tblImportTransaction();

                trax = fx.GetTransactionFX(line, CurrentUser.Peoplewise, DateTime.Now);
                trax.CreatedBy = CurrentUser.Peoplewise;

                trax.Branch = branch;
                trax.CustomerName = cusName;

                trax.Status = 0;
                tblImportTransactionService.CreatetblImportTransaction(trax);
                traxColection.Add(trax);
              }
            }
          }
        }
      }
      catch (Exception ex)
      {
        Logger.Error("WebRobot.Pages.ImportPage::ReadReportFX", ex);
        throw;
      }
      return traxColection;
    }

    public tblImportTransactionCollection ReadReportOther(string sFilePath)
    {


      string fullPath = sFilePath;

      string sFileName = sFilePath.Split('\\')[sFilePath.Split('\\').Length - 1];
      tblImportTransactionCollection traxColection = new tblImportTransactionCollection();
      string branch = "";
      DateTime dateReport = new DateTime();

      string text = BasePage.PdfToText(fullPath); int t = 0;
      try
      {
        using (StringReader lines = new StringReader(text))
        {
          OtherFileReport other = new OtherFileReport();
          string line = "";
          while ((line = lines.ReadLine()) != null)
          {
            if (line != "")
            {
              if (other.IsBranchCodeOther(line))
              {
                branch = other.GetBranchOther(line);
              }
              else if (other.IsDateOfReportOther(line))
              {
                dateReport = other.GetDateOfReportOther(line);
              }
              else if (other.IsTransaction(line))
              {
                t++;
                tblImportTransaction trax = new tblImportTransaction();
                trax = other.GetTransactionOther(line, DateTime.Now);
                trax.FromFileID = tblFileUploadService.GettblFileUploadByFileName(sFileName, CurrentUser.Peoplewise).ID;
                trax.CreatedBy = CurrentUser.Peoplewise;
                trax.Branch = branch;
                trax.ApprovedBy = null;
                trax.ValueDate = dateReport;
                trax.Status = 0;
                tblImportTransactionService.CreatetblImportTransaction(trax);
                traxColection.Add(trax);
              }
            }
          }
        }
      }
      catch (Exception ex)
      {
        Logger.Error("WebRobot.Pages.ImportPage::ReadReportOther", ex);
        throw;
      }
      return traxColection;
    }

    #endregion

  }
}
